<template>
</template>

<script>
import { getRootWindow } from '@src/util/platform'
import { weChatIdConvert2UserId } from '@src/api/WechatApi'

export default {
  name: 'base-wx-contact-dept-user',
	props: {
    max: {
      type: Number,
      default: 0
    },
    selectedUser: {
      type: Array,
      default: () => []
    },
    selectedDepts: {
      type: Array,
      default: () => ([])
    }
	},
	computed: {
		type() {
			return ['user']
		},
		mode(){
		return this.max != 1  ? 'multi' : 'single';
		},
		selectedDepartmentIds() {
			return []
		},
		selectedUserIds() {
			return this.selectedUser.map(item => {
				return item.staffId
			})
		}
	},
  mounted() {
  	const rootWindow = getRootWindow(window);
	const that = this
		
    rootWindow.wx.invoke(
    	'selectEnterpriseContact',
    	{
    		"fromDepartmentId": -1, // 必填，表示打开的通讯录从指定的部门开始展示，-1表示自己所在部门开始, 0表示从最上层开始
        	"mode": this.mode, // 必填，选择模式，single表示单选，multi表示多选
        	"type": this.type, // 必填，选择限制类型，指定department、user中的一个或者多个
        	"selectedDepartmentIds": this.selectedDepartmentIds, // 非必填，已选部门ID列表。用于多次选人时可重入，single模式下请勿填入多个id
        	"selectedUserIds": this.selectedUserIds // 非必填，已选用户ID列表。用于多次选人时可重入，single模式下请勿填入多个id
    	},
		async function (res) {
			if (res.err_msg == "selectEnterpriseContact:ok") {
				let data = {}
				if(typeof res.result == 'string') {
					res.result = JSON.parse(res.result) //由于目前各个终端尚未完全兼容，需要开发者额外判断result类型以保证在各个终端的兼容性
				}
				console.log('selectEnterpriseContact -- res.result', res.result)

				// departmentList-已选的部门列表, userList-已选的成员列表 {id, name, avatar}
				const { userList, departmentList } = res.result
				const wxUserIds = userList.map(item => item.id) // 微信通讯录组件选中的ids
				
				// 微信选中的ids => [{"staffId":"", "userId":""}]
				let covertUserItems = []
				await weChatIdConvert2UserId({userIdList: wxUserIds})
					.then(res=> {
						if(res.succ) covertUserItems = res.data
					})
          		console.log('selectEnterpriseContact -- covertUserItems', covertUserItems)
				
				// 使用转换后的系统内id 添加人员
				const selectedUserList = userList.map((item, index) => {
					const { userId = '', staffId = '' } = covertUserItems[index] || {}
					return {
						userId: userId,
						displayName: item.name,
						staffId: staffId,
						head: item.avatar
					}
				})
				data.users = selectedUserList
          		console.log('selectEnterpriseContact -- selectedUserList', data)
				that.$emit('success', data)
			} else {
				console.log('selectEnterpriseContact -- error', res)
			}
		}
    )
  },
}
</script>

<style>

</style>